<template>
  <a-drawer
    title="新建调整"
    :maskClosable="true"
    :visible="visible"
    :width="$store.getters.isMobile ? 350 : 800"
    :body-style="{
      paddingBottom: '80px',
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
      overflowY: 'auto',
    }"
    @close="onCancel"
  >
    <a-alert type="info" v-if="!haveApprove">
      <template #message>
        调整金暂未开启审批，如需开启审批，请前往”财务-所有账单-更多-审批配置“中设置，点击”<span
          class="link"
          @click.stop="goSetting"
          >配置</span
        >“可快速设置。
      </template>
    </a-alert>
    <a-form layout="vertical">
      <a-row :gutter="[12, 12]" :wrap="true">
        <a-col :span="24">
          <a-alert
            v-if="showAlert"
            message="当前账单已开具发票/收据，请谨慎调整账单价格"
            show-icon
            :closable="true"
            :after-close="handleAlertClose"
          />
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 12">
          <a-form-item label="调整类型" v-bind="validateInfos.adjust_type">
            <a-select
              v-model:value="modelRef.adjust_type"
              placeholder="请选择调整类型"
            >
              <a-select-option
                v-for="item of initData.adjustType"
                :value="item.key"
                :key="item.key"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 12">
          <a-form-item label="调整时间" v-bind="validateInfos.adjust_date">
            <a-date-picker
              class="w-100p"
              v-model:value="modelRef.adjust_date"
              :valueFormat="dateFormatStr"
            />
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 12">
          <a-form-item label="调整方式" v-bind="validateInfos.adjust_mode">
            <a-select
              v-model:value="modelRef.adjust_mode"
              placeholder="请选择调整方式"
            >
              <a-select-option
                v-for="item of initData.adjustMode"
                :value="item.key"
                :key="item.key"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="$store.getters.isMobile ? 24 : 12">
          <a-form-item
            label="调整比例"
            v-bind="validateInfos.adjust_num"
            v-if="modelRef.adjust_mode == 2"
          >
            <a-input-number
              style="width: 140px"
              placeholder="请输入调整比例"
              :min="0"
              v-model:value="modelRef.adjust_num"
            />
            <span class="ml-5" style="margin-right: 15px">%</span>
            <span v-if="adjustPrice" style="margin-left: 3px; color: red"
              >{{ reduce ? "- " : "+ " }}{{ adjustPrice }} 元</span
            >
            <span v-if="adjustPrice" style="margin-left: 3px; color: red"
              >= {{ final_price }} 元
            </span>
          </a-form-item>
          <a-form-item
            label="调整金额"
            v-bind="validateInfos.adjust_num"
            v-else
          >
            <a-input-number
              style="width: 140px; margin-right: 15px"
              placeholder="请输入调整金额"
              v-model:value="modelRef.adjust_num"
              :min="0"
            />
            <span v-if="adjustPrice" style="margin-left: 3px; color: red"
              >{{ reduce ? "- " : "+ " }}{{ adjustPrice }} 元</span
            >
            <span v-if="adjustPrice" style="margin-left: 3px; color: red"
              >= {{ final_price }} 元
            </span>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="备注" v-bind="validateInfos.remark">
            <a-textarea
              placeholder="请输入备注内容"
              :auto-size="{ minRows: 3 }"
              v-model:value="modelRef.remark"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="附件" >
            <a-upload-dragger
                v-model:fileList="fileList"
                name="file"
                :multiple="true"
                :action="$utils.fileAction"
                :headers="{ 'org-token': $store.getters.token }"
                :showUploadList="false"
                @change="handleUploadChange"
                :defore-upload="beforeUpload"
                accept=".doc,.docx,.pdf,.xlsx,.jpg,.jpeg,.png"
                :data="{ dir: 'org_contract_add_attachments' }"
            >
              <div>
                <p class="ant-upload-drag-icon"> <InboxOutlined /> </p>
                <p class="ant-upload-text"> 拖拽文件至虚线款内或点击此区域上传文件 </p>
                <p class="ant-upload-hint">文档只支持doc、docx、pdf、xlsx、jpg、jpeg、png格式</p>
              </div>
            </a-upload-dragger>

            <div v-if="modelRef.files.length > 0" style="margin-top: 15px;">
              <a-table
                  :dataSource="modelRef.files"
                  :columns="devicecolumns"
                  :pagination="false"
                  row-key="id"
                  :scroll="{ x: 'max-content' }"
              >
                <template #bodyCell="{ text, record, column }">
                  <template v-if="column.key === 'file_name'">
                    <a-input v-model:value="record.file_name" />
                  </template>
                  <template v-if="column.key === 'file_url'">
                    <div style="width: 300px;text-align: left;">
                      {{text}}
                    </div>
                  </template>
                  <template v-if="column.key === 'receive'">
                    <a-tooltip>
                      <template #title>在线预览</template>
                      <a-button v-if="record.file_url && !(record.file_url.indexOf('.doc') != -1 || record.file_url.indexOf('.docx') != -1
                                  || record.file_url.indexOf('.pdf') != -1 || record.file_url.indexOf('.xlsx') != -1)"
                                type="link" @click="previewClick(record)" >
                        <template #icon>
                          <EyeOutlined />
                        </template>
                      </a-button>
                    </a-tooltip>
                    <a-tooltip >
                      <template #title>下载</template>
                      <a-button v-if="record.file_url && !(record.file_url.indexOf('.jpg') != -1 || record.file_url.indexOf('.jpeg') != -1 || record.file_url.indexOf('.png') != -1)"
                                type="link" @click="downloadFile(record.file_url)">
                        <template #icon>
                          <DownloadOutlined />
                        </template>
                      </a-button>
                    </a-tooltip>
                    <a-tooltip >
                      <template #title>删除</template>
                      <a-button type="link" danger @click="deleteFile(record)" >
                        <template #icon>
                          <DeleteOutlined />
                        </template>
                      </a-button>
                    </a-tooltip>
                  </template>
                </template>
              </a-table>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onCancel">取消</a-button>
        <a-button type="primary" @click.prevent="onSubmit">{{
          haveApprove ? "保存&发起审批" : "保存"
        }}</a-button>
      </a-space>
    </div>

    <!--  审批配置  -->
    <BillApprovalSetting
      :visible="approvalVisible"
      @closeModal="closeApproval"
    />

    <PreviewImg
        :visible="imgVisible"
        :index="0"
        :list="imgList"
        @close="imgVisible = false"
    />

    <electronContractModal
        :visible="electronContractVisible"
        :esignDetail="{ esignCheck: true }"
        @close="electronContractVisible = false"
        @refresh="electronContractVisible = false"
        type="contractDetail"
        title="在线预览"
        :urlData="previewUrlData"
    />

  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  reactive,
  watch,
  ref,
  toRefs,
  createVNode,
} from "vue";
import request from "../../../../common/utils/request";
import store from "../../../../store";
import { Form, message, Modal } from "ant-design-vue";
import moment from "moment";
import BillApprovalSetting from "@/components/contract/CustomFilter/modules/BillApprovalSetting.vue";
import electronContractModal from "@/components/ElectronContractModal/index.vue";
import {
  DeleteOutlined, DownloadOutlined,
  ExclamationCircleOutlined, EyeOutlined,
  FileOutlined,
  FileTextOutlined,
  FolderOutlined,
  InboxOutlined,
} from "@ant-design/icons-vue";
import utils from "@/common/utils/utils";
import _ from "lodash";
import { PreviewImg } from "bl-common-vue3";
const useForm = Form.useForm;
const dateFormatStr = "YYYY-MM-DD";
const devicecolumns = [
  {
    title: "名称",
    dataIndex: "file_name",
    key: "file_name",
    align: "center",
  },
  {
    title: "网址",
    dataIndex: "file_url",
    key: "file_url",
    align: "center",
    width: 300 ,
  },
  {
    title: "操作",
    dataIndex: "receive",
    key: "receive",
    align: "center",
  },
];

export default defineComponent({
  name: "AddAdjust",
  components: {
    EyeOutlined, DownloadOutlined, DeleteOutlined, PreviewImg,electronContractModal,
    FolderOutlined, FileOutlined, InboxOutlined, FileTextOutlined, BillApprovalSetting },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    initData: {
      type: Object,
      default: () => ({
        adjustMode: [], // 调整方式
        adjustType: [], // 调整类型
      }),
    },
  },
  setup(props, context) {
    const today = moment();

    const showAlert = ref(false);
    const handleAlertClose = () => {
      showAlert.value = false;
    };
    const state = reactive({
      // 是否有审批
      haveApprove: true,
      approvalVisible: false,
      final_price: 0,

      fileList:[],
      imgVisible:false,
      imgList:'',
      electronContractVisible:false,
    });

    const modelRef = reactive({
      adjust_type: undefined,
      adjust_date: today,
      adjust_mode: undefined,
      adjust_num: "",
      remark: "",
      files:[],
    });
    const ruleRef = reactive({
      adjust_type: [{ required: true, message: "必选" }],
      adjust_date: [{ required: true, message: "必选" }],
      adjust_mode: [{ required: true, message: "必选" }],
      adjust_num: [{ required: true, message: "必填" }],
    });

    const { resetFields, validate, validateInfos } = useForm(modelRef, ruleRef);

    const adjustPrice = computed(() => {
      console.log(modelRef);
      if (modelRef.adjust_num) {
        const isReduce = modelRef.adjust_type != 2;
        if (modelRef.adjust_mode == 1) {
          let amount = store.getters.billMatchAccountDetail.receiveAmount;
          state.final_price = isReduce
            ? utils.countSum([amount, -Number(modelRef.adjust_num)])
            : utils.countSum([amount, Number(modelRef.adjust_num)]);
          state.final_price = _.round(state.final_price, 2);
          console.log(state.final_price);
          return Number(modelRef.adjust_num);
        } else if (modelRef.adjust_mode == 2) {
          let amount = store.getters.billMatchAccountDetail.receiveAmount;
          let scaleData = (amount * (Number(modelRef.adjust_num) / 100)).toFixed(2)
          state.final_price = isReduce ? utils.countSum([amount, -scaleData]) : utils.countSum([amount, scaleData])
          state.final_price = _.round(state.final_price, 2);
          return scaleData;
        }
      } else {
        return 0;
      }
    });

    const reduce = computed(() => {
      if (modelRef.adjust_type) {
        if (modelRef.adjust_type == 2) {
          return false;
        } else {
          if (modelRef.adjust_num) {
            return true;
          }
          return false;
        }
      }
      return false;
    });

    const onCancel = () => {
      state.fileList = []
      context.emit("cancel");
    };

    const onSubmit = () => {
      validate().then(() => {
        let params = {
          bill_id: store.getters.billMatchAccountDetail.bill_id,
          ...modelRef,
          needMsg: true,
        };
        params.adjust_date = moment(params.adjust_date).format(dateFormatStr);
        request
          .post("/org", "/bill/addAdjust", {
            ...params,
          })
          .then((res) => {
            message.success(res.msg || "保存成功！");
            context.emit("success");
          })
          .catch((err) => {
            if (err.code == 12001) {
              Modal.confirm({
                title: () => "提示",
                content: () =>
                  err?.msg || "您需要先设置调整审批流程才能调整金额哦~",
                icon: () => createVNode(ExclamationCircleOutlined),
                centered: true,
                okText: () => "前往",
                onOk() {
                  onCancel();
                  if (window.__MICRO_APP_ENVIRONMENT__) {
                    window.microApp.forceDispatch({
                      type: "SetMicroPages",
                      microInfo: {
                        microId: `org_workApproval_manage_index`,
                        app: 'workApproval',
                        name: '管理审批',
                        url: `/approval/manage/index`,
                      }
                    })
                  }
                },
              });
            }
          });
      });
    };

    const handleUploadChange = (info) => {
      console.log(info)
      let resFileList = [ ...info.fileList ];
      if (resFileList.length) {
        resFileList = resFileList.map((file, index) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              // 上传失败
              message.warning(file.response.msg);
              file.fail = true;
            }
          }
          return file;
        });
      }
      resFileList = resFileList.filter((file) => !file.fail);
      let list = []
      for (let i = 0; i < resFileList.length; i++) {
        list.push({
          file_name:resFileList[i].name,
          file_url:resFileList[i].url,
        })
      }
      modelRef.files = list
    };

    const beforeUpload = (file) => {
      return new Promise((resolve, reject) => {
        const isLt2M = file.size / 1024 / 1024 <= 50;
        if (!isLt2M) {
          message.warn("文件大小不能超过50M");
          return reject(false)
        }
        return resolve(true);
      })
    };

    const previewUrlData = ref({});

    const previewClick = (record) => {
      /*if (record.file_url.indexOf('.doc') != -1 || record.file_url.indexOf('.docx') != -1 || record.file_url.indexOf('.pdf') != -1 || record.file_url.indexOf('.xlsx') != -1) {
        previewUrlData.value = {
          url: record.file_url,
          previewUrl: '',
        };
        state.electronContractVisible = true;
        return;
      }*/
      if (record.file_url.indexOf('.jpg') != -1 || record.file_url.indexOf('.jpeg') != -1 || record.file_url.indexOf('.png') != -1) {
        state.imgList = [record.file_url];
        state.imgVisible = true;
      }
    };

    // 下载文件
    const downloadFile = (url) => {
      if (!url) {
        message.error("未返回文件路径，无法下载");
        return;
      }
      window.open(url);
    };

    // 删除文件
    const deleteFile = (item) => {
      for (let i = 0; i < modelRef.files.length; i++) {
        if(modelRef.files[i].file_name == item.file_name){
          modelRef.files.splice(i , 1)
          state.fileList.splice(i , 1)
        }
      }
    };

    const getSetting = () => {
      // 获取配置
      request.get("/org", "/bill/approvalGet").then((res) => {
        state.haveApprove = !!res?.config?.find(
          (v) => v.type === "adjust_approve"
        )?.is_use;
      });
    };

    const goSetting = () => {
      state.approvalVisible = true;
    };

    const closeApproval = () => {
      state.approvalVisible = false;
      getSetting();
    };

    const init = () => {
      showAlert.value = store.getters.billMatchAccountDetail.issue_flag;
      getSetting();
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetFields();
          state.haveApprove = true;
        }
        state.fileList = []
      }
    );

    return {
      ...toRefs(state),
      dateFormatStr,
      modelRef,
      validateInfos,
      adjustPrice,
      showAlert,
      onCancel,
      onSubmit,
      handleAlertClose,
      goSetting,
      closeApproval,
      reduce,
      handleUploadChange,
      devicecolumns,
      previewUrlData,
      previewClick,
      downloadFile,
      deleteFile,
      beforeUpload,
    };
  },
});
</script>
